package com.sphd.beautysalon.activitys.sale;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.beautysalon.activitys.OrderParticularsActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.info.SalesInfo;
import com.sphd.beautysalon.presenter.SalesPresenterImpl;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.adapters.SalesAdapter;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.userView.SrarchTime;
import com.sphd.beautysalon.view.SalesView;
import com.wzh.frame.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 店铺的销售
 */
public class RestaurantSalesActivity extends BaseActivity implements SalesView, SrarchTime.DateListener {

    @BindView(R.id.spinner_orders_type)
    Spinner spinnerOrdersType;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private static final String TAG = "RestaurantSalesActivity";
    Intent intent;
    Bundle bundle;
    int TYPE = 0; //sppiner的type
    int FLAG = 0;//三个按钮的标志
    int DATETYPE = 0;// 0为显示年 1为月 2 为日
    @BindView(R.id.topup_textview)
    TextView topupTextview;
    @BindView(R.id.orders_num)
    TextView ordersNum;
    @BindView(R.id.content_restaurant_sales)
    LinearLayout contentRestaurantSales;
    @BindView(R.id.in_order)
    TextView inOrder;
    @BindView(R.id.out_order)
    TextView outOrder;
    @BindView(R.id.entering_order)
    TextView enteringOrder;
    String url;
    int cgId;
    RestaurantInfo restaurantInfo;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.action_search)
    ImageView actionSearch;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.topup_textview_all)
    TextView topupTextviewAll;

    private int curpage = 1;
    SalesInfo salesInfo;
    SalesAdapter salesAdapter;
    SalesPresenterImpl salesPresenter;
    boolean isOver = false;
    String starTime;
    String endTime;
    boolean isSerach = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restaurant_sales);
        ButterKnife.bind(this);
        setTitleBar(toolbar, "销售量");
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        myRecy.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                salesInfo = (SalesInfo) baseQuickAdapter.getItem(i);
                if (!isSerach) {
                    starTime = salesInfo.getTime();
                    endTime = salesInfo.getTime();
                }
                if (DATETYPE == 4) {
                    if (FLAG != 2) {
                        bundle.putSerializable(Constant.SALESINFO, salesInfo);
                        intent.putExtras(bundle);
                        startActivity(OrderParticularsActivity.class, bundle);
                    }
                } else {
                    selectUrl();
                    addData();
                }
            }
        });

        mySwf.setOnRefreshListener(() -> {
            if (isOver) {

                DATETYPE = DATETYPE - 1;
            }
            curpage = 1;
            selectUrl();
            addData();
        });

        salesAdapter.setOnLoadMoreListener(() -> {
            curpage++;
            if (isOver) {
                DATETYPE = DATETYPE - 1;
            }
            selectUrl();
            addData();
        });
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        TYPE = bundle.getInt(Constant.TYPE);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        cgId = restaurantInfo.getId();
        salesPresenter = new SalesPresenterImpl(this);
        initAdapter();
        // TODO: 2016/11/4 当 setSelection（）只包含一个参数值得时候会自动调用 setOnItemSelectedListener（）方法
        //如果setSelection(1，true)；则不会调用 setOnItemSelectedListener（）方法
//        spinnerOrdersType.setSelection(bundle.getInt(Constant.TYPE),true);
        initSpinner();
    }

    private void initAdapter() {
        setRefresh(mySwf);
        setRecy(myRecy);
        salesAdapter = new SalesAdapter(R.layout.item_all_sale, new ArrayList<SalesInfo>(), this);
        myRecy.setAdapter(salesAdapter);
        salesAdapter.openLoadAnimation();
        salesAdapter.openLoadMore(10);
    }

    private void initSpinner() {
        spinnerOrdersType.setSelection(TYPE);
        spinnerOrdersType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TYPE = i;
                initNoAndGetData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initNoAndGetData() {
        if (!isSerach) {
            if (TYPE == 0) {
                DATETYPE = 3;
            } else if (TYPE == 1) {
                DATETYPE = 2;
            } else if (TYPE == 2) {
                DATETYPE = 0;
            }
        } else {
            DATETYPE = 3;
        }
        curpage = 1;
        selectUrl();
        addData();
    }


    private void addData() {
        isOver = false;
        salesPresenter.addData(url);
    }

    private void selectUrl() {
        Log.e("TYPE===", TYPE + "");
        if (TYPE == 0) {
            url = RestaurantUrl.Httptitle + RestaurantUrl.SalesAndOrdersThreeNum + "cgid=" + cgId + "&type=" + TYPE +
                    "&isosale=" + FLAG + "&curpage=" + curpage + "&pageno=10";
        } else if (TYPE == 1) {
            if (DATETYPE == 2) {
                url = RestaurantUrl.Httptitle + RestaurantUrl.ADDUPDAY + "cgid=" + cgId + "&month="
                        + TimeUtils.getMont(Calendar.getInstance())
                        + "&isosale=" + FLAG;
            } else {
                url = RestaurantUrl.Httptitle + RestaurantUrl.SearchSalesAndOrdersThreeNum + "cgid=" + cgId +
                        "&starttime=" + starTime + "&endtime=" + endTime
                        + "&isosale=" + FLAG
                        + "&curpage=" + curpage + "&pageno=10";
            }
        } else if (TYPE == 2) {
            if (DATETYPE == 0) {
                //年的数据展示
                url = RestaurantUrl.Httptitle + RestaurantUrl.ADDUP + "cgid=" + cgId + "&isosale=" + FLAG;
            } else if (DATETYPE == 1) {
                //月份的数据展示
                url = RestaurantUrl.Httptitle + RestaurantUrl.ADDUPMONTH + "cgid=" + cgId
                        + "&year=" + salesInfo.getTime() + "&isosale=" + FLAG;
            } else if (DATETYPE == 2) {
                //获取日的数据展示
                url = RestaurantUrl.Httptitle + RestaurantUrl.ADDUPDAY + "cgid=" + cgId +
                        "&month=" + salesInfo.getTime()
                        + "&isosale=" + FLAG;
            } else if (DATETYPE == 3) {
                url = RestaurantUrl.Httptitle + RestaurantUrl.SearchSalesAndOrdersThreeNum + "cgid=" + cgId +
                        "&starttime=" + starTime + "&endtime=" + endTime
                        + "&isosale=" + FLAG
                        + "&curpage=" + curpage + "&pageno=10";
            }
        }
    }


    @Override
    public void setText(double topup, double inMoeny, double outMoney, double enterMoney, int listNo) {
        topupTextviewAll.setText("销售额："+turn(topup+inMoeny+outMoney+enterMoney));
        topupTextview.setText("\t其中充值金额:\t" + turn(topup) + "\n");
        inOrder.setText("\n店内\n" + turn(inMoeny) + "\n");
        outOrder.setText("\n外卖\n" + turn(outMoney) + "\n");
        enteringOrder.setText("\n录入订单\n" + turn(enterMoney) + "\n");
        ordersNum.setText("共有" + listNo + "笔订单");
    }

    @Override
    public void recRes(List<SalesInfo> salesInfos) {
        salesAdapter.setType(DATETYPE, FLAG);
        if (curpage == 1) {
            salesAdapter.setNewData(salesInfos);
        } else {
            salesAdapter.addData(salesInfos);
        }
        addfootView(salesInfos);
        changeDATETYPE();
        isOver = true;

    }

    private void addfootView(List<SalesInfo> salesInfos) {
        if (salesInfos.size() != 10) {
            salesAdapter.loadComplete();
            addFootView(salesAdapter);
        }
    }

    /**
     * 通过改变DATETYPE更换请求的url
     */
    private void changeDATETYPE() {
        DATETYPE++;
    }

    @OnClick({R.id.in_order, R.id.out_order, R.id.entering_order})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.in_order:
                if (FLAG != 0) {
                    FLAG = 0;
                    initNoAndGetData();
                }
                break;
            case R.id.out_order:
                if (FLAG != 1) {
                    FLAG = 1;
                    initNoAndGetData();
                }
                break;
            case R.id.entering_order:
                if (FLAG != 2) {
                    FLAG = 2;
                    initNoAndGetData();
                }
                break;
        }
        changeTextColorAndBackground(FLAG);
    }

    //设置滑动或者选中高亮
    private void changeTextColorAndBackground(int position) {
        setImageviewBackground();
        switch (position) {
            case 0:
                inOrder.setTextColor(getResources().getColor(R.color.indigo_500));
                break;
            case 1:
                outOrder.setTextColor(getResources().getColor(R.color.indigo_500));
                break;
            case 2:
                enteringOrder.setTextColor(getResources().getColor(R.color.indigo_500));
                break;
            default:
                break;
        }
    }

    //设置滑动或者改变后的清空背景色
    private void setImageviewBackground() {
        enteringOrder.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        outOrder.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        inOrder.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        inOrder.setTextColor(getResources().getColor(R.color.black));
        outOrder.setTextColor(getResources().getColor(R.color.black));
        enteringOrder.setTextColor(getResources().getColor(R.color.black));
    }

    @OnClick(R.id.action_search)
    public void onClick() {
        SrarchTime srarchTime = new SrarchTime(this);
        srarchTime.setDateListener(this);
        srarchTime.showSearchTime();
    }

    @Override
    public void getDate(String startDate, String endDate) {
        Log.e("S", startDate);
        Log.e("S2", endDate);
        spinnerOrdersType.setVisibility(View.GONE);
        time.setText(startDate + "~" + endDate);
        curpage = 1;
        TYPE = 2;
        FLAG = 0;
        changeTextColorAndBackground(0);
        DATETYPE = 3;
        starTime = startDate;
        endTime = endDate;
        isSerach = true;
        selectUrl();
        addData();
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
        mySwf.setRefreshing(false);
    }
}
